import Vue from 'vue';
import loadingVue from './Loading.vue';

const LoadingTemplate = Vue.extend(loadingVue);

const toggleLoading = (el, binding) => {
  if (binding.value) {
    if (Array.from(el.instance.$el.classList).indexOf('close') > -1) {
      el.instance.$el.classList.remove('close');
    } else {
      el.appendChild(el.instance.$mount().$el);
    }
  } else {
    el.instance.$el.classList.add('close');
  }
};

export default {
  bind: function(el, binding) {
    const instance = new LoadingTemplate({
      el: document.createElement('div')
    });
    el.instance = instance;
    binding.value && toggleLoading(el, binding);
  },
  update: function(el, binding) {
    toggleLoading(el, { value: false });
    toggleLoading(el, binding);
  },
  unbind: function(el) {
    setTimeout(() => {
      toggleLoading(el, { value: false });
    }, 200);
  }
};
